package org.example.demo.controller;

import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/web3")
public class Web3Controller {

    @Autowired
    private Client client;

    /**
     * 获取当前账户信息
     */
    @GetMapping("/account")
    public Map<String, Object> getAccount() {
        Map<String, Object> result = new HashMap<>();
        try {
            CryptoKeyPair keyPair = client.getCryptoSuite().getCryptoKeyPair();
            
            result.put("success", true);
            result.put("account", keyPair.getAddress());
            result.put("publicKey", keyPair.getHexPublicKey());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取账户信息失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 提供JSON-RPC代理接口，用于前端与区块链节点通信
     */
    @PostMapping("/jsonrpc")
    public Map<String, Object> jsonRpc(@RequestBody Map<String, Object> requestBody) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 这里应该实现对FISCO BCOS节点的JSON-RPC调用
            // 由于FISCO BCOS使用的是自定义的JSON-RPC，需要根据具体接口进行处理
            // 作为示例，这里只返回区块高度
            Object blockNumber = client.getBlockNumber();
            
            response.put("jsonrpc", "2.0");
            response.put("id", requestBody.getOrDefault("id", 1));
            
            Map<String, Object> result = new HashMap<>();
            result.put("blockNumber", blockNumber);
            response.put("result", result);
            
        } catch (Exception e) {
            response.put("jsonrpc", "2.0");
            response.put("id", requestBody.getOrDefault("id", 1));
            
            Map<String, Object> error = new HashMap<>();
            error.put("code", -32603);
            error.put("message", "内部错误: " + e.getMessage());
            response.put("error", error);
        }
        return response;
    }

    /**
     * 获取区块链状态信息
     */
    @GetMapping("/status")
    public Map<String, Object> getStatus() {
        Map<String, Object> result = new HashMap<>();
        try {
            result.put("success", true);
            result.put("blockNumber", client.getBlockNumber());
            result.put("pbftView", client.getPbftView());
            result.put("peers", client.getPeers());
            result.put("nodeVersion", client.getNodeVersion());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取区块链状态失败: " + e.getMessage());
        }
        return result;
    }
} 